type Listener = (data: any) => void

const subscribeMap = new Map<string, Listener[]>()

export const subscribe = (key: string, listener: Listener) => {
  if (!subscribeMap.has(key)) {
    subscribeMap.set(key, [listener])
  } else {
    subscribeMap.get(key).push(listener)
  }

  return () => {
    const listeners = subscribeMap.get(key)
    const index = listeners.indexOf(listener)
    listeners.splice(index, 1)
  }
}

export const trigger = (key: string, data: any) => {
  if (subscribeMap.has(key)) {
    subscribeMap.get(key).forEach(listener => listener(data))
  }
}
